#! -*- coding:utf-8 -*-
import os
import json
import logging
from datetime import datetime

from async import async_job
from common.order import admin_db as order_db
from common.channel.channel_map import CHANNEL_HANDLER
from common.channel import admin_db as channel_db
from common.channel.pay.trpay import query_charge

from django.core.management.base import BaseCommand, CommandError


_LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):

    def handle(self, order_id, **options):
        order_id = int(order_id)
        order = order_db.get_order(id=order_id)
        if order.status != 0: # 支付成功或失败，重新回调
            async_job.notify_mch.delay(order_id)
        else:
            # 未支付，调用通道接口查询订单状态
            chn = channel_db.get_channel(order.channel_id)
            chn_info = json.loads(chn.info)
            app_id = chn_info.get('app_id')
            chn_handler = CHANNEL_HANDLER[order.channel_type]
            chn_handler.query_charge(order, app_id)
